﻿using Admin.NET.Application.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http.Headers;
using Admin.NET.Core.Helper;
using WTM.Lutools.ViewModel.Helper;

namespace WTM.Lutools.Service.Kerryplus;

public class KerryplusService
{
    private readonly SqlSugarRepository<Kerrypluscarinfo> _kerryPlusCarInfoRepository;
    private readonly SqlSugarRepository<Kerrypluscarorder> _kerryPlusCarOrderRepository;
    private readonly SqlSugarRepository<Kerryplususerinfo> _kerryPlusUserInfoRepository;
    private readonly ILogger<KerryplusService> _logger;

    public KerryplusService(ILogger<KerryplusService> logger, IConfiguration iConfiguration,
        SqlSugarRepository<Kerrypluscarinfo> kerryPlusCarInfoRepository,
        SqlSugarRepository<Kerryplususerinfo> kerryPlusUserInfoRepository,
        SqlSugarRepository<Kerrypluscarorder> kerryPlusCarOrderRepository)
    {
        _logger = logger;
        _kerryPlusCarInfoRepository = kerryPlusCarInfoRepository;
        _kerryPlusUserInfoRepository = kerryPlusUserInfoRepository;
        _kerryPlusCarOrderRepository = kerryPlusCarOrderRepository;
    }

    /// <summary>
    ///     自动缴费 06.19版本
    /// </summary>
    public void AotuCarOrdersPlus0619()
    {
        try
        {
            //_logger.LogInformation($"开始自动缴费任务~");
            //筛选出需要缴费的车牌
            //每个整点 多查一次全部
            List<Kerrypluscarinfo> carList;
            var chechOut = false;
            if (DateTime.Now.Minute == 30)
            {
                chechOut = true;
                //任何时候还没出场的
                carList = _kerryPlusCarInfoRepository.AsQueryable()
                    .Where(x => (x.IsAutoPay || x.IsAutoQuery) && x.State == 2)

                    .ToList();
                if (DateTime.Now.Hour % 2 == 0)
                {
                    chechOut = false;
                    _logger.LogInformation("每两小时都把所有在场内的车尝试缴费一次");
                }
            }
            else if ((DateTime.Now.Hour >= 6 && DateTime.Now.Hour <= 23) || DateTime.Now.Minute == 0)
            {
                //6-24的随时扫描
                carList = _kerryPlusCarInfoRepository.AsQueryable()
                    .Where(x => (x.IsAutoPay || x.IsAutoQuery)
                                && (x.TodayCouponCount == 0 || x.TodayIntegral < 200)
                    //&& !x.todayOut
                    )

                    .ToList();
            }
            else
            {
                //任何时候还没出场的
                carList = _kerryPlusCarInfoRepository.AsQueryable()
                    .Where(x => (x.IsAutoPay || x.IsAutoQuery) && x.State == 2
                                                               && (x.TodayCouponCount == 0 || x.TodayIntegral < 200))

                    .ToList();
            }

            if (carList?.Count > 0)
                foreach (var car in carList)
                    if (car != null)
                    {
                        var carNo = car.CarNo;

                        //#if DEBUG
                        //                    //伪装15分钟前入场了
                        //                    car.EnterTime = DateTime.Now.AddMinutes(-15);
                        //                    car.State = 2;
                        //#endif
                        var lSpan = DateTime.Now - car.EnterTime;
                        if (lSpan.TotalMinutes < 15 /*|| lSpan.TotalMinutes > 600*/)
                            //_logger.LogInformation($"{CarNo}从{car.EnterTime:yyyy-MM-dd HH:mm:ss}开始停,未停足15分钟,不做查询");
                            continue;

                        //if (car.State == 2 && lSpan.TotalMinutes > 602 && (int)lSpan.TotalMinutes % 60 != 0)
                        //{
                        //    //_logger.LogInformation($"{CarNo}从{car.EnterTime:yyyy-MM-dd HH:mm:ss}开始停,超过了10小时,每小时查一次");
                        //    continue;
                        //}
                        if ((car.State == 2 && car.IsAutoPay && car.TotalFeeInYuan > 0) ||
                            (car.State == 2 && (int)lSpan.TotalMinutes % 5 == 1) ||
                            (car.State != 2 && ((int)lSpan.TotalMinutes + car.Id) % 15 == 0) ||
                            (car.State == 2 && car.LastQueryTime < DateTime.Now.AddMinutes(-8)) ||
                            (car.State != 2 && car.LastQueryTime < DateTime.Now.AddMinutes(-18)
                                            && car.IsAutoPay))
                        {
                            if (chechOut || (car.IsAutoQuery && !car.IsAutoPay) || car.NextPayTime > DateTime.Now)
                            {
                                _logger.LogInformation($"{carNo}只查询不缴,只用积分最高的号查询下欠费");
                                var userInfoList = _kerryPlusUserInfoRepository.AsQueryable()
                                    .Where(x => x.State == 1 && !string.IsNullOrWhiteSpace(x.UnionId))
                                    .WhereIF(car.TodayCouponCount == 0, x => x.TodayCouponCount == 0)
                                    .WhereIF(car.TodayCouponCount > 0 && car.TodayIntegral < 200,
                                        x => x.TodayIntegral < 200)
                                    .OrderByDescending(x => x.CurrnentIntegral).Skip(0).Take(10)
                                    .ToList();
                                if (userInfoList.Count > 0)
                                {
                                    var random = new Random();
                                    var randomIndex = random.Next(userInfoList.Count); // 先生成随机索引

                                    // 直接通过索引获取随机元素
                                    var randomUserInfo = userInfoList[randomIndex];

                                    var selectUserId = randomUserInfo.UserId;
                                    if (!string.IsNullOrWhiteSpace(selectUserId))
                                        //找个号来查一下
                                        GainParkingCheck(selectUserId, carNo);
                                }

                                continue;
                            }

                            _logger.LogInformation($"开始{carNo}自动查询任务");
                            var thisDay = DateTime.Today;
                            var thisMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01");
                            //这句别删 后面规则有用
                            var dayOrders = _kerryPlusCarOrderRepository.AsQueryable()
                                .Where(x => x.CarNo == carNo && x.EnterTime >= thisDay).ToList();

                            //规则
                            var payRule = car.PayRule;
                            //应缴积分数
                            var totalFeeInIntegral = car.TotalFeeInYuan * 10;
                            if (totalFeeInIntegral < 50) totalFeeInIntegral = 50;
                            if (string.IsNullOrWhiteSpace(payRule)) payRule = "2,0,0,0,0,0,0,0";
                            var payRules = payRule.Split(',');
                            var dayOrdersCount = dayOrders.Count;
                            var thisPayRule = "1";
                            try
                            {
                                thisPayRule = payRules[dayOrdersCount];
                                if (thisPayRule != "0" && thisPayRule != "1" && thisPayRule != "2")
                                    //如果规则写错了 直接用1小时券
                                    thisPayRule = "1";
                                if (DateTime.Today != new DateTime(2024, 5, 11)
                                    && DateTime.Today != new DateTime(2024, 9, 14)
                                    && DateTime.Today != new DateTime(2024, 9, 29)
                                    && DateTime.Today != new DateTime(2024, 10, 12))
                                    if (thisPayRule == "1")
                                    {
                                        var dayOfWeek = DateTime.Now.DayOfWeek;
                                        if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
                                            //周末如果是1小时券 自动换2小时
                                            thisPayRule = "2";
                                    }
                            }
                            catch (Exception e)
                            {
                                //如果规则写错了 直接用2小时券
                                thisPayRule = "2";
                            }

                            if (totalFeeInIntegral > 150)
                            {
                                thisPayRule = "2";
                                _logger.LogInformation($"{carNo}欠费超过15元,使用规则{thisPayRule},开始开挑选查询缴费信息账号");
                            }

                            if (totalFeeInIntegral > 450)
                            {
                                _logger.LogError($"{carNo}欠费超过45元,使用规则{thisPayRule},无法自动缴费");

                                var mgs =
                                    $"#### 应缴金额大于45元通知  \n > {carNo} 从 {car.EnterTime}({car.TodayCouponCount},{car.TodayIntegral}) 到 {DateTime.Now:yyyy-MM-dd HH:mm:ss} ~\n > 现应缴费用{car.TotalFeeInYuan}元,无法使用自动缴费 \n > 点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                                _ = DingtalkWebHookHelper.SendMessage(mgs);

                                continue;
                            }

                            _logger.LogInformation($"{carNo}欠费{car.TotalFeeInYuan:F}元,使用规则{thisPayRule},开始开挑选查询缴费信息账号");

                            if (car.TodayCouponCount > 0)
                                thisPayRule = "0";
                            else if (car.TodayIntegral >= 200 && thisPayRule == "0") thisPayRule = "2";
                            /*
                            var userId = GanSelectUser0619(int.Parse(thisPayRule), totalFeeInIntegral);

                            if (!string.IsNullOrWhiteSpace(userId))
                            {
                                var i = OrdersAndPrepayPlus(userId, CarNo, true, 0, int.Parse(thisPayRule));
                                if (i == 1)
                                {
                                    //缴费成功多休眠3秒
                                    Thread.Sleep(500);
                                }
                            }
                            else
                            {
                                var selectUserId = _kerryPlusUserInfoRepository
                                    .Where(x => x.State == 1 && !string.IsNullOrWhiteSpace(x.UnionId) && x.CurrnentIntegral >= 200).Where(x => x.todayIntegral <= 200 - totalFeeInIntegral)
                                    .OrderByDescending(x => x.usePriority).ThenByDescending(x => x.CurrnentIntegral).Select(x => x.UserId).First() ?? "";
                                if (!string.IsNullOrWhiteSpace(selectUserId))
                                {
                                    if (1 == 2)
                                    {
                                        _logger.LogError($"给{CarNo}缴费时,选号出错,先用积分最高的号查询下欠费");
                                        //找个号来查一下
                                        GainParkingCheck(selectUserId, CarNo);
                                    }
                                    else
                                    {
                                        _logger.LogError($"给{CarNo}缴费时,选号出错,先用积分最高的号缴费");
                                        OrdersAndPrepayPlus(selectUserId, CarNo, true, 0, int.Parse(thisPayRule));
                                    }
                                }
                            }
                            */
                            //每辆车隔3秒
                            Thread.Sleep(500);
                        }
                    }
        }
        catch (Exception e)
        {
            var mgs =
                $"#### 错误通知 \n >  自动缴费错误:{e.Message} ~\n > 请进入系统确认信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

            _ = DingtalkWebHookHelper.SendMessagePlus(mgs);
            _logger.LogError(e, "自动缴费错误");
        }
    }

    /// <summary>
    ///     查询缴费信息
    /// </summary>
    public ParkingCheckOutResp GainParkingCheck(string userId, string carNo, int isHand = 0)
    {
        if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(carNo)) return null;

        carNo = carNo.ToUpper();

        var userInfo = _kerryPlusUserInfoRepository.AsQueryable().First(x => userId == x.UserId);
        var carInfo = _kerryPlusCarInfoRepository.AsQueryable().First(x => carNo == x.CarNo.ToUpper());

        return GainParkingCheck2(userInfo, carInfo, isHand);
    }

    /// <summary>
    ///     查询缴费信息
    /// </summary>
    public ParkingCheckOutResp GainParkingCheck2(Kerryplususerinfo userInfo, Kerrypluscarinfo car, int isHand = 0)
    {
        //#if DEBUG

        //        var parkingCheckData =
        //            $@"{{""parkingRecord"":{{""vehicleNo"":""粤BA5K21"",""enterTime"":""2024-01-03 11:38:22"",""serviceMin"":32,""totalFee"":1500,""actualPayFee"":0.0,""thirdPartyId"":""DqwsT0MPtOnouQJLKkK4Sq"",""thirdParkOrderNo"":""Cyn5QLrQFNvYJdrHlTgqTe"",""createdByQrCode"":false,""totalFeeInYuan"":15.00}},""discountInfo"":{{""usingTotalDiscount"":20,""memberLevelDiscount"":false,""points"":[{{""available"":535,""maxDiscountFee"":20,""pointsPerUnit"":50,""unitAmount"":5,""totalAvailable"":535,""newMember"":false,""label"":""535积分可减免""}}],""coupons"":[{{""code"":""3vlhdi0jfjj_t"",""couponId"":""f36676be991e4c5e9d520be35f731b0c"",""status"":""available"",""name"":""首2小时免费停车券"",""expirationDate"":""2024-01-31 23:59:59"",""discountFee"":20,""defaultSelected"":true,""superposition"":""1"",""limitCountPerOrder"":0}},{{""code"":""djupvx3ct2q_t"",""couponId"":""f57ad3fa0cb945a0b69d4c2bcba3fc9d"",""status"":""available"",""availableDays"":""工作日"",""name"":""首1小时免费停车券（工作日）"",""expirationDate"":""2024-03-31 23:59:59"",""discountFee"":15,""defaultSelected"":false,""superposition"":""1"",""limitCountPerOrder"":0}}]}},""parkingRule"":{{""maxOneDayDiscountFee"":60,""enableNewMemberPoints"":false,""enablePoints"":true,""unLimitWeekendPoints"":false,""enableCoupon"":true,""enablePaperCoupons"":false,""maxPointsTime"":10,""enableConsume"":false,""enableConsumeNonSplit"":false,""availableDiscountFee"":60,""hourPrice"":5,""oneTimeLimitation"":false,""oneDayLimitation"":true}},""parkInfo"":{{""parkName"":""QHKC"",""description"":""计费基础规则：15分钟内免费，首小时15元，其后每小时5元，全天封顶60元。\n嘉湾汇会员停车礼遇：\n银卡：每月可免费领取2张首2小时停车券\n金卡：每月可免费领取5张首2小时停车券\n铂金卡：每月可免费领取10张首2小时停车券\n*数量有限，领完即止\n仅限开具一个月内的停车费电子发票 "",""ruleDescription"":"""",""parkMallCode"":5,""buildingId"":""10047"",""isCrmSupport"":1}}}}";

        //        return JsonConvert.DeserializeObject<ParkingCheckOutResp>(parkingCheckData);

        //#endif
        var carNo = car.CarNo;
        var userId = userInfo.UserId;
        if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(carNo)) return null;

        carNo = carNo.ToUpper();
        var token = userInfo.Token;
        var isLogin = !string.IsNullOrWhiteSpace(token) && CheckToken(ref token);

        if (isLogin && !string.IsNullOrWhiteSpace(userInfo.UnionId))
        {
            var url =
                $"https://apim.kerryplus.com/c/api/temporary-parking/v1/parking/check-out?vehicleNo={Uri.EscapeDataString(carNo)}&unlicensed=false";

            var pUser =
                $"{{\"userId\":\"{userInfo.UserId}\",\"sourceType\":\"WECHAT\",\"phoneNumber\":\"{userInfo.PhoneNumber}\",\"brandId\":\"{userInfo.BrandId}\",\"cid\":\"{userInfo.OpenId}\",\"vipCode\":\"{userInfo.VipCode}\",\"lbsId\":\"{userInfo.LbsId}\",\"sourceId\":\"{userInfo.UnionId}\",\"isLogin\":true}}";

            var headDictionary = new Dictionary<string, string>();
            headDictionary.Add("Parking-User", pUser);

            var currentRespResult = HttpHelper.CallApi<dynamic>(url, token, headDictionary);
            _logger.LogInformation(userInfo.PhoneNumber + "," + carNo + ":查询缴费信息返回:" +
                                   JsonConvert.SerializeObject(currentRespResult));

            var isUpdate = false;
            var parkingCheckOutResp = new ParkingCheckOutResp();

            if (currentRespResult?.StatusCode == HttpStatusCode.OK)
            {
                var currentResp = currentRespResult.Data;
                try
                {
                    if (currentResp?.ToString() == "false")
                    {
                        var mgs =
                            $"#### 接口返回数据异常通知 {(isHand == 1 ? "(手动)" : "")} \n > {userInfo.PhoneNumber}({userInfo.TodayCouponCount},{userInfo.TodayIntegral}) 查询 {car.CarNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) \n > 返回信息 \n > {JsonConvert.SerializeObject(currentRespResult)} \n > 点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                        _ = DingtalkWebHookHelper.SendMessagePlus(mgs);
                        return parkingCheckOutResp;
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "接口返回数据异常通知:" + JsonConvert.SerializeObject(currentRespResult));
                    return parkingCheckOutResp;
                }

                parkingCheckOutResp =
                    JsonConvert.DeserializeObject<ParkingCheckOutResp>(JsonConvert.SerializeObject(currentResp));

                if (parkingCheckOutResp != null)
                {
                    var parkingRecord = parkingCheckOutResp?.ParkingRecord;
                    if (parkingRecord != null)
                    {
                        decimal totalFee = 0;
                        var defaultCouponStr = "";
                        try
                        {
                            if (parkingRecord?.TotalFee > 0)
                            {
                                totalFee = parkingRecord?.TotalFee ?? 0;

                                var coupons = parkingCheckOutResp?.DiscountInfo?.Coupons;

                                if (coupons?.Count > 0)
                                {
                                    var defaultCoupon = coupons?.Where(x => x.DefaultSelected.ToLower() == "true")
                                        ?.First();
                                    if (defaultCoupon != null) defaultCouponStr = ",预计将使用:" + defaultCoupon.Name;
                                }

                                if (string.IsNullOrWhiteSpace(defaultCouponStr))
                                    defaultCouponStr = ",预计会用积分缴费(选号不对也会出现提示)";
                            }
                        }
                        catch
                        {
                        }

                        var serviceMinStr = "";
                        try
                        {
                            serviceMinStr =
                                $"({(parkingRecord.ServiceMin / 60).ToString().PadLeft(2, '0')}:{(parkingRecord.ServiceMin % 60).ToString().PadLeft(2, '0')})";
                        }
                        catch
                        {
                        }

                        if (car.State != 2)
                        {
                            var mgs =
                                $"#### 进场通知 {(isHand == 1 ? "(手动)" : "")} \n > {userInfo.PhoneNumber}({userInfo.TodayCouponCount},{userInfo.TodayIntegral}) 查询 {parkingRecord.VehicleNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) 于 {parkingRecord.EnterTime} 停进来啦,已经停了{parkingRecord.ServiceMin}分钟{serviceMinStr}~\n > 现应缴费用{totalFee}元 {defaultCouponStr} \n > 点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                            _ = DingtalkWebHookHelper.SendMessage(mgs);
                        }
                        else if (car.TotalFeeInYuan != totalFee)
                        {
                            var mgs =
                                $"#### 应缴金额变更通知 {(isHand == 1 ? "(手动)" : "")} \n > {userInfo.PhoneNumber}({userInfo.TodayCouponCount},{userInfo.TodayIntegral}) 查询 {parkingRecord.VehicleNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) 从 {parkingRecord.EnterTime} 到 {DateTime.Now:yyyy-MM-dd HH:mm:ss} 已经停了{parkingRecord.ServiceMin}分钟{serviceMinStr}, 缴费金额有变更~\n > 现应缴费用{totalFee}元 {defaultCouponStr} \n > 点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                            _ = DingtalkWebHookHelper.SendMessage(mgs);
                        }
                        else if (totalFee > 0)
                        {
                            var mgs =
                                $"#### 应缴金额大于0元通知 {(isHand == 1 ? "(手动)" : "")} \n > {userInfo.PhoneNumber}({userInfo.TodayCouponCount},{userInfo.TodayIntegral}) 查询 {parkingRecord.VehicleNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) 从 {parkingRecord.EnterTime} 到 {DateTime.Now:yyyy-MM-dd HH:mm:ss} 已经停了{parkingRecord.ServiceMin}分钟{serviceMinStr}, 缴费金额有变更~\n > 现应缴费用{totalFee}元 {defaultCouponStr} \n > 点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                            _ = DingtalkWebHookHelper.SendMessage(mgs);
                        }
                        else
                        {
                            var lSpan = DateTime.Now - car.EnterTime;

                            if (car.State == 2 && (int)lSpan.TotalMinutes % 60 >= 55 &&
                                (int)lSpan.TotalMinutes % 60 < 60)
                            {
                                var mgs =
                                    $"#### 整点停放通知 {(isHand == 1 ? "(手动)" : "")} \n > {userInfo.PhoneNumber}({userInfo.TodayCouponCount},{userInfo.TodayIntegral}) 查询 {parkingRecord.VehicleNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) 从 {parkingRecord.EnterTime} 到 {DateTime.Now:yyyy-MM-dd HH:mm:ss} 已经停了{parkingRecord.ServiceMin}分钟{serviceMinStr} ~\n >  点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                                _ = DingtalkWebHookHelper.SendMessage(mgs);
                            }
                        }

                        DateTime.TryParse(parkingCheckOutResp.ParkingRecord.EnterTime, out var enterTime);
                        car.TotalFeeInYuan = totalFee;
                        car.EnterTime = enterTime;
                        car.LastQueryTime = DateTime.Now;
                        car.State = 2;
                        isUpdate = true;

                        _logger.LogInformation(
                            $"{userInfo.PhoneNumber} ({userInfo.TodayCouponCount},{userInfo.TodayIntegral})查询 {parkingRecord.VehicleNo}({car.Remark})({car.TodayCouponCount},{car.TodayIntegral}) 从 {parkingRecord.EnterTime} 到 {DateTime.Now:yyyy-MM-dd HH:mm:ss} 已经停了{parkingRecord.ServiceMin}分钟{serviceMinStr},现应缴费用{totalFee}元");
                        try
                        {
                            //DateTime.TryParse(parkingCheckOutResp.parkingRecord.EnterTime, out DateTime enterTime);
                            var lastOrder = _kerryPlusCarOrderRepository.AsQueryable().OrderByDescending(x => x.Id)
                                .First(x => x.CarNo == carNo && x.EnterTime == enterTime);

                            if (lastOrder != null)
                            {
                                lastOrder.ServiceMin = parkingRecord.ServiceMin;
                                _kerryPlusCarOrderRepository.Update(lastOrder);
                            }
                        }
                        catch
                        {
                            _logger.LogInformation("更新服务时间错误!!换种写法");
                            try
                            {
                                //DateTime.TryParse(parkingCheckOutResp.parkingRecord.EnterTime, out DateTime enterTime);
                                var lastOrder = _kerryPlusCarOrderRepository.AsQueryable()
                                    .Where(x => x.CarNo == carNo && x.EnterTime == enterTime).ToList()
                                    .LastOrDefault();

                                if (lastOrder != null)
                                {
                                    lastOrder.ServiceMin = parkingRecord.ServiceMin;
                                    _kerryPlusCarOrderRepository.Update(lastOrder);
                                }
                            }
                            catch (Exception e)
                            {
                                _logger.LogError(e,
                                    "更新服务时间错误");
                            }
                        }
                    }
                    else
                    {
                        if (car.TotalFeeInYuan != 0 || car.State != 1)
                        {
                            car.TotalFeeInYuan = 0;
                            car.EnterTime = DateTime.MinValue;
                            car.LastQueryTime = DateTime.Now;
                            car.State = 1;
                            isUpdate = true;
                        }
                    }
                }
            }
            else if (currentRespResult?.StatusCode == HttpStatusCode.Conflict)
            {
                if (car.TotalFeeInYuan != 0 || car.State != 1)
                {
                    if (car.State == 2)
                    {
                        var timeMsg = "";
                        try
                        {
                            var lastOrder = _kerryPlusCarOrderRepository.AsQueryable().OrderByDescending(x => x.Id)
                                .First(x => x.CarNo == carNo);

                            if (lastOrder != null) timeMsg = "预计停了" + lastOrder.ServiceMin + "分钟.";
                        }
                        catch
                        {
                        }

                        car.TodayOut = true;
                        var mgs =
                            $"#### 离场通知 {(isHand == 1 ? "(手动)" : "")} \n > {carNo}({car.TodayCouponCount},{car.TodayIntegral}) 出去了~ {timeMsg} \n >  点击详情查看具体信息! \n > ###### {DateTime.Now:HH点mm分ss秒}发布 [详情](https://49b6z1955.yicp.fun/) \n";

                        _ = DingtalkWebHookHelper.SendMessage(mgs);
                    }

                    car.TotalFeeInYuan = 0;
                    car.EnterTime = DateTime.MinValue;
                    car.LastQueryTime = DateTime.Now;
                    car.State = 1;
                    isUpdate = true;
                }
                else
                {
                    //记录下最后的查询时间
                    car.LastQueryTime = DateTime.Now;
                    isUpdate = true;
                }
            }

            if (isUpdate) _kerryPlusCarInfoRepository.Update(car);

            return parkingCheckOutResp;
        }

        _logger.LogInformation($"{userInfo.PhoneNumber}未登录,不能查询和缴费");
        return null;
    }

    /// <summary>
    ///     检查token是否有效
    /// </summary>
    public bool CheckToken(ref string token)
    {
        if (token.IndexOf("Bearer ") > -1) token = token.Replace("Bearer ", "");
        var url = "https://apim.kerryplus.com/c/api/oauth/v1/customer/users/checkToken?token=" + token;

        var currentRespResult = HttpHelper.CallApi<dynamic>(url, token);

        if (currentRespResult?.StatusCode == HttpStatusCode.OK)
        {
            var currentResp = currentRespResult.Data;

            var userInfo = currentResp;
            var phoneNumber = userInfo?.PhoneNumber;
            if (phoneNumber != null) return true;
        }
        else if (currentRespResult?.StatusCode == HttpStatusCode.Unauthorized)
        {
            var tokenInfoStr = JwtTokenHelper.JwtTokenDecode(token);
            var tokenInfo = JsonConvert.DeserializeObject<dynamic>(tokenInfoStr);
            var userTokenInfo = tokenInfo?.user;
            //
            if (userTokenInfo != null)
            {
                string userId = userTokenInfo.userId;
                var refreshToken = _kerryPlusUserInfoRepository.AsQueryable().First(x => x.UserId == userId)
                                       ?.RefreshToken ??
                                   "";

                var refToken = ExecuteRefreshToken(refreshToken);
                if (!string.IsNullOrWhiteSpace(refToken))
                {
                    token = refToken;
                    return true;
                }
            }
        }

        _logger.LogInformation("CheckToken.获取用户信息失败:" + currentRespResult?.ErrorMsg);

        return false;
    }

    /// <summary>
    ///     重新获取Token
    /// </summary>
    public string ExecuteRefreshToken(string refreshToken)
    {
        if (string.IsNullOrWhiteSpace(refreshToken)) return "";
        var url = "https://apim.kerryplus.com/c/api/oauth/v1/oauth/renewToken?refreshToken=" + refreshToken;

        var sc = new StringContent("null");
        sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        sc.Headers.ContentType.CharSet = "utf-8";
        var renewTokenRespResult = HttpHelper.CallApi<dynamic>(url, HttpMethodEnum.POST, sc, "");

        if (renewTokenRespResult?.StatusCode == HttpStatusCode.OK)
        {
            var renewTokenResp = renewTokenRespResult?.Data;
            _logger.LogInformation($"刷新Token返回:{JsonConvert.SerializeObject(renewTokenResp)}");

            if (renewTokenResp?.code == 300001)
            {
                var tokenInfoStr = JwtTokenHelper.JwtTokenDecode(refreshToken);
                var tokenInfo = JsonConvert.DeserializeObject<dynamic>(tokenInfoStr);
                var userTokenInfo = tokenInfo?.user;
                //
                if (userTokenInfo != null)
                {
                    string userId = userTokenInfo.userId;

                    var userInfo = _kerryPlusUserInfoRepository.AsQueryable()
                        .Where(x => x.UserId == userId).First();
                    if (userInfo != null)
                    {
                        userInfo.State = -2;
                        //_kerryPlusUserInfoRepository.Update(userInfo);

                        _logger.LogInformation($"更新登录状态为{userInfo.State}:{JsonConvert.SerializeObject(userInfo)}");
                    }
                }
            }
            else
            {
                var renewTokenRespData = renewTokenResp?.data;
                string token = renewTokenRespData.access_token;
                var tokenInfoStr = JwtTokenHelper.JwtTokenDecode(token);
                var tokenInfo = JsonConvert.DeserializeObject<dynamic>(tokenInfoStr);
                string userIda = tokenInfo.user.userId;
                var userInfo = _kerryPlusUserInfoRepository.AsQueryable()
                    .Where(x => userIda == x.UserId).First();
                if (userInfo != null)
                {
                    userInfo.Token = token;

                    long timestamp = tokenInfo?.exp ?? 0;
                    var dateTime = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                    userInfo.TokenUpdateTime = dateTime.LocalDateTime.AddDays(-1);

                    userInfo.RefreshToken = renewTokenRespData.refresh_token;

                    userInfo.LastTime = DateTime.Now;
                    userInfo.State = 1;

                    //_kerryPlusUserInfoRepository.Update(userInfo);

                    _logger.LogInformation("刷新token成功,phoneNumber:" + userInfo.PhoneNumber);
                    return userInfo.Token;
                }
            }
        }

        return "";
    }
}